package com.analyse.stock.service.impl;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.util.StrUtil;
import com.alibaba.fastjson.JSONObject;
import com.analyse.stock.constant.ApiConstant;
import com.analyse.stock.constant.StockConstant;
import com.analyse.stock.enums.BoardCategoryEnum;
import com.analyse.stock.mapper.BoardCategoryMapper;
import com.analyse.stock.model.BoardCategoryModel;
import com.analyse.stock.service.IBoardCategory;
import com.analyse.stock.utils.HttpUtil;
import com.analyse.stock.utils.StockStringUtil;
import com.analyse.stock.vo.FundFlowDataVO;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Service;

import java.util.Arrays;
import java.util.List;
import java.util.Objects;
import java.util.stream.Collectors;

@Slf4j
@Service
public class BoardCategoryService extends ServiceImpl<BoardCategoryMapper, BoardCategoryModel> implements IBoardCategory {

    @Override
    public Integer pullBoardCategoryList(String boardCodes) {
        List<String> codes = StringUtils.isNotBlank(boardCodes)? Arrays.asList(boardCodes.split(StrUtil.COMMA)):null;
        for(BoardCategoryEnum categoryEnum : BoardCategoryEnum.values()){
            //为空 全部执行
            //不为空是 等于code 的执行
            if(CollUtil.isNotEmpty(codes) && !codes.contains(categoryEnum.getCode())){
                continue;
            }
            long time = System.currentTimeMillis()*1001;
            String url = StrUtil.format(ApiConstant.BOARD_URL,categoryEnum.getCode(),time);
            String result = HttpUtil.sendGet(url,"*/*", StockConstant.UTF8,6000L);
            if(StringUtils.isBlank(result)){
                continue;
            }
            JSONObject jsonObject = JSONObject.parseObject(result);
            if(jsonObject.getInteger("rc") != 0 || Objects.isNull(jsonObject.get("data"))){
                continue;
            }
            FundFlowDataVO dataVO = StockStringUtil.getObject(jsonObject.getString("data"), FundFlowDataVO.class);
            log.info("## 板块:{}, 开始解析 最新的板块分类数据-----",categoryEnum.getDesc());
            List<BoardCategoryModel> models = dataVO.getDiff().stream()
                    .map(e->BoardCategoryModel.transBoardCategoryModel(e,categoryEnum.name())).collect(Collectors.toList());
            super.saveBatch(models);
        }
        return null;
    }

    @Override
    public List<BoardCategoryModel> getBoardCategoryList(String boardCodes) {
        if(StringUtils.isBlank(boardCodes)){
            return super.list();
        }
        LambdaQueryWrapper<BoardCategoryModel> wrapper = new LambdaQueryWrapper<>();
        wrapper.in(BoardCategoryModel::getBoardCode,Arrays.asList(boardCodes.split(StrUtil.COMMA)));
        return super.list(wrapper);
    }
}
